<?php
/**
 * Обработчик ошибок
 * Выводи (не)приятное сообщение
 * с трейслогом и фрагментами кода
 *
 */
class ErrorHandlerAction extends \Action {

	protected function run() {

		$error = $this->request->error;
		$trace = $this->request->trace;

		$errorCode = $this->request->error ['code'];
		if (404 == $errorCode) {
			$this->response->code ( $errorCode, 'Not Found' );
		} elseif (403 == $errorCode) {
			$this->response->code ( $errorCode, 'Forbidden' );
		}  elseif (500 <= $errorCode) {
			$this->response->code ( $errorCode, 'Internal server error' );
		}
		
		$commonPath = static::getCommonPath ();

		$pos = $error ['line'];
		$error ['codeText'] = static::getCode ( $error ['file'], $pos );
		$error['file'] = str_replace($commonPath, "", $error['file']);
		
		$this->response->error = $error;
		
		foreach ( $trace as &$t ) {
			// получаем девять строк из файла
			if (isset ( $t ['file'] )) {
				$pos = $t ['line'];
				$t ['code'] = static::getCode ( $t ['file'], $pos );
				$t['file'] = str_replace($commonPath, "", $t['file']);
			}
		}
		
		// $trace = static::doArray ( $trace );
		
		$this->response->trace = $trace;

		// для консольного тупо выводим
		if (\Application::isConsole ()) {
			$this->response->noRender ( true );
			print_r ( $error );
			print_r ( $trace );
		}
	}
	static function getCode($name, $pos) {
		$arr = [ ];
		if ($pos > 4)
			$pos -= 5;
		$file = array_slice ( file ( $name ), $pos, 9 );
		$mass = explode ( "<br />", highlight_file ( $name, true ) );
		foreach ( $file as $key => $val ) {
			$arr [$key + $pos + 1] = rtrim ( $mass [$key + $pos] );
		}
		return $arr;
	}
	
	static function getCommonPath() {
		$path = explode ( PATH_SEPARATOR, get_include_path () );
		foreach ( $path as $el ) {
			$commonArr [] = realpath ( $el );
		}
		$array_result = null;
		foreach ( $commonArr as $el ) {
			if (empty ( $array_result )) {
				$array_result = explode ( "/", $el );
			} else {
				$array_result = array_intersect_assoc ( $array_result, explode ( "/", $el ) );
			}
		}
		return implode ( "/", $array_result );
	}
}